package common

import (
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"log"
	"strconv"
	"three-sxp/models/mysql"
)

type Pay interface {
	Payment(order mysql.Order) (string, error)
}
type AliPay struct {
	AppId      string
	PrivateKey string
	PublicKey  string
}

var ali AliPay
var AliClient *alipay.Client

func init() {
	var err error
	ali.AppId = "9021000131622561"
	ali.PrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCNeR7RJ6IlUCzKOI50I/7DcFS3cyPEUVGWdLLe8eV4g7n/4lMc0H6qn//7RDYXWm1Bwha7zUXzKGnfrEB4YCiduhLT6B5h4j+mzbIMFQZ1aoPC/+aTYA7ZYK4NrA8Jj9EEZpH0J3D4x9LlshnGFuJHjI68XbDhR/+aOOxENAKLw3TQAWANVkh21xtolmPfDvE29eEYQYosStzk8jpV5WLmC9X8ualkr9XJWQT7T+gQsqBR3IyS0seYa0ExF5KByHfQw2nxq9bx3yoKikxlcZvc6NU7w5e+lsuRZ7Xh8bYKk8TnBw+bXZ74ZS/LajZwpwXR4p4HmOyKFzxrUG7gPP0jAgMBAAECggEAO7CFuxNwyzN3ol6YZBIn1EfZxojy50q0FLnqGjyPZ/iUCo1wKbEiMFVPiLEv7Ux+2obMVrJ2N/CuMuwXS3Ku0FWIyhWedAgkePlCjOx2DCZDr4uOulGGEltDNIuK0Kr4MlYgcJYPiTeuGLG7RCO1lyCLvJf/IB3jjytDLEeRZ2wOshjtfZWzbXbzoM/2hr4YpMVcsiZvFIdO23NVPeh9iARjXwmze8D+MZ+LxZW+GjmfsEKL1qMasBnBi4KCUn16c5C3GoB/UQ7b5ZmlpMgp2CpAEt8PvSh3PtVPLw/Mmke6z1XK610DXAUQSiVyCF2tr7pThvV6z7EnTrQ+tYcDuQKBgQDdlv24+M/bu7xA2TLHXf0eP3UYhRVJhRTUKupp5JTgwSmjkpycyACyJ79UmaFbF+Xnm5859rC+gj4At05pk9j3ZWmqfdj1Mn4SWONx+BXlZTptHywyWPs4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d8qCopMZXGb3OjVO8OXvpbLkWe14fG2CpPE5wcPm12e+GUvy2o2cKcF0eKeB5jsihc8a1Bu4Dz9IwIDAQAB"
	AliClient, err = alipay.New(ali.AppId, ali.PrivateKey, false)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = AliClient.LoadAliPayPublicKey(ali.PublicKey)
	if err != nil {
		log.Println("初始化失败")
	}
}

func (a *AliPay) Payment(order mysql.Order) (string, error) {
	m := strconv.FormatFloat(order.Money, 'f', -1, 64)
	var p = alipay.TradeWapPay{}
	p.NotifyURL = "http://xxx"
	p.ReturnURL = "http://xxx"
	p.Subject = "尚鑫平"
	p.OutTradeNo = order.UserSn
	p.TotalAmount = m
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	var url, err = AliClient.TradeWapPay(p)
	if err != nil {
		fmt.Println(err)
	}

	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	var payURL = url.String()
	fmt.Println(payURL)
	return payURL, nil
}
